package com.hondee.fuzzyquery.entity.access;

import org.springframework.jdbc.core.JdbcTemplate;

import com.hondee.fuzzyquery.entity.DBMultilineResultsEntity;
import com.hondee.fuzzyquery.entity.Entity;
import com.hondee.fuzzyquery.utils.SQLCreator;

/**
 * SqlServer Table访问
 * @author Allen
 *
 */
public class SqlServerTableAccess  extends AbstractEntityAccess {
	
	private JdbcTemplate jdbcTemplate;
	
	public SqlServerTableAccess(String accessId,DBQuery query,JdbcTemplate jdbcTemplate){
		super(accessId,query);
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Entity<?> access() {
		DBQuery dbquery = (DBQuery)query;
		
		StringBuilder orderStr = new StringBuilder();
		if(dbquery.getOrder()!=null){
			for(QueryOrder order : dbquery.getOrder()){
				orderStr.append(order).append(",");
			}
		}
		
		StringBuilder fieldsStr = new StringBuilder();
		if(dbquery.getQueryFields()!=null){
			for(String field : dbquery.getQueryFields()){
				fieldsStr.append(field).append(",");
			}
		}
		
		String sql = null;
		String sqlCount = null;
		if(dbquery.getIsPaging()){
			sql = SQLCreator.getSqlServerSqlWithColumns(dbquery.getPageIndex()
					, dbquery.getPageSize()
					, dbquery.getTable()
					, dbquery.getCondition().toString()
					, orderStr.length()>0? orderStr.subSequence(0, orderStr.length()-1).toString():""
					, fieldsStr.length()>0? fieldsStr.subSequence(0, fieldsStr.length()-1).toString():"");
			
		}else{
			sql = SQLCreator.getSqlServerSqlNoPaging(dbquery.getTable()
					, fieldsStr.length()>0? fieldsStr.subSequence(0, fieldsStr.length()-1).toString():""
					, dbquery.getCondition().toString()
					, orderStr.length()>0? orderStr.subSequence(0, orderStr.length()-1).toString():"");
		}
		sqlCount = SQLCreator.getSqlServerSqlCount(dbquery.getTable(), dbquery.getCondition().toString());
		
		return new DBMultilineResultsEntity(accessId,jdbcTemplate.queryForList(sql),jdbcTemplate.queryForObject(sqlCount, Integer.class));
	}
	
}
